package com.code.google.wormon;

import java.io.IOException;

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.Control;
import javax.sound.sampled.FloatControl;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;

public enum WormonSoundFx {
	EXPLODE("com/code/google/wormon/resources/explode.wav"), 
	SHOOT("com/code/google/wormon/resources/shoot.wav"), 
	ZOOP("com/code/google/wormon/resources/zoop.wav"),
	ALERT("com/code/google/wormon/resources/alert.wav");

	public enum Volume {
		MUTE(0.0f), LOW(50f), MEDIUM(75f), HIGH(100f);
		private Float value;

		Volume(Float value) {
			this.value = value;
		}

		public Float getValue() {
			return value;
		}
	}

	public Volume volume = Volume.HIGH;

	private Clip clip;

	WormonSoundFx(String soundFileName) {
		try {
			AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(this.getClass().getClassLoader().getResourceAsStream(soundFileName));
			clip = AudioSystem.getClip();
			clip.open(audioInputStream);
			Control[] controls = clip.getControls();
			FloatControl volumeControl = null;
			for (Control control : controls) {
				if (control.getType().equals(FloatControl.Type.MASTER_GAIN)) {
					volumeControl = (FloatControl) control;
					float minimum = volumeControl.getMinimum();
					float maximum = volumeControl.getMaximum();
					float newValue = (float) (minimum + volume.getValue() * (maximum - minimum) / 100.0F);
					volumeControl.setValue(newValue);
				}

				if (control.getType().equals(FloatControl.Type.VOLUME)) {
					volumeControl = (FloatControl) control;
					float minimum = volumeControl.getMinimum();
					float maximum = volumeControl.getMaximum();
					float newValue = (float) (minimum + volume.getValue() * (maximum - minimum) / 100.0F);
					volumeControl.setValue(newValue);
				}

			}
		} catch (UnsupportedAudioFileException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (LineUnavailableException e) {
			e.printStackTrace();
		}
	}

	public void play() {
		if (volume != Volume.MUTE) {
			if (clip.isRunning()) {
				clip.stop();
			}
			clip.setFramePosition(0);
			clip.start();
		}
	}
	
	public void playOnce(){
		if (!clip.isRunning()) {
			clip.setFramePosition(0);
			clip.start();
		}
	}
	
	public void stop() {
		clip.stop();
	}

}
